<template>
  <div class="volume-viewer">
    <div class="toolbar">
      <el-button-group>
        <el-button
          v-for="layout in layouts"
          :key="layout.type"
          :type="currentLayout === layout.type ? 'primary' : 'default'"
          @click="setLayout(layout.type)"
        >
          <el-icon>
            <component :is="layout.icon" />
          </el-icon>
          {{ layout.label }}
        </el-button>
      </el-button-group>

      <el-divider direction="vertical" />

      <el-button-group>
        <el-button
          v-for="mode in renderModes"
          :key="mode.type"
          :type="currentMode === mode.type ? 'primary' : 'default'"
          @click="setRenderMode(mode.type)"
        >
          {{ mode.label }}
        </el-button>
      </el-button-group>

      <el-divider direction="vertical" />

      <div class="view-controls">
        <el-tooltip content="重置视图">
          <el-button @click="resetView">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="截图">
          <el-button @click="takeScreenshot">
            <el-icon><Camera /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="分割分析">
          <el-button type="primary" @click="goToSegmentation">
            <el-icon><Edit /></el-icon>
            分割分析
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <div class="viewer-container" ref="container">
      <div v-for="view in activeViews" 
           :key="view.id" 
           :class="['vtk-view', `layout-${currentLayout}`]"
           :ref="view.id">
      </div>
    </div>

    <div class="side-panel">
      <el-collapse v-model="activePanel">
        <el-collapse-item title="体渲染设置" name="volume">
          <div class="panel-content">
            <el-form label-position="top" size="small">
              <el-form-item label="不透明度">
                <el-slider v-model="volumeOpacity" :min="0" :max="100" @change="updateVolumeProperty" />
              </el-form-item>
              <el-form-item label="亮度">
                <el-slider v-model="brightness" :min="0" :max="200" @change="updateVolumeProperty" />
              </el-form-item>
              <el-form-item label="对比度">
                <el-slider v-model="contrast" :min="0" :max="200" @change="updateVolumeProperty" />
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
        
        <el-collapse-item title="切割平面" name="clipping">
          <div class="panel-content">
            <el-form label-position="top" size="small">
              <el-form-item label="矢状面">
                <el-slider v-model="clipPlanes.sagittal" :min="0" :max="100" @change="updateClipPlanes" />
              </el-form-item>
              <el-form-item label="冠状面">
                <el-slider v-model="clipPlanes.coronal" :min="0" :max="100" @change="updateClipPlanes" />
              </el-form-item>
              <el-form-item label="横断面">
                <el-slider v-model="clipPlanes.axial" :min="0" :max="100" @change="updateClipPlanes" />
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  Camera, 
  Refresh,
  Grid,
  Edit
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow'
import vtkVolume from '@kitware/vtk.js/Rendering/Core/Volume'
import vtkVolumeMapper from '@kitware/vtk.js/Rendering/Core/VolumeMapper'
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction'
import vtkPiecewiseFunction from '@kitware/vtk.js/Common/DataModel/PiecewiseFunction'

const router = useRouter()
const route = useRoute()

// 视图布局
const layouts = [
  { type: 'single', label: '单视图', icon: 'monitor' },
  { type: 'double', label: '双视图', icon: Grid },
  { type: 'triple', label: '三视图', icon: Grid },
  { type: 'quad', label: '四视图', icon: Grid }
]

// 渲染模式
const renderModes = [
  { type: 'mip', label: '最大密度投影' },
  { type: 'average', label: '平均密度投影' },
  { type: 'composite', label: '复合' }
]

const container = ref(null)
const currentLayout = ref('single')
const currentMode = ref('composite')
const activePanel = ref(['volume'])
const volumeOpacity = ref(100)
const brightness = ref(100)
const contrast = ref(100)
const clipPlanes = ref({
  sagittal: 100,
  coronal: 100,
  axial: 100
})

// VTK.js 相关变量
let renderWindow: any
let renderer: any
let volumeActor: any
let volumeMapper: any

// 从路由状态获取体数据
const volumeData = computed(() => {
  return (router.currentRoute.value as any).state?.volumeData
})

// 视图配置
const activeViews = computed(() => {
  switch (currentLayout.value) {
    case 'single':
      return [{ id: 'main' }]
    case 'double':
      return [{ id: 'left' }, { id: 'right' }]
    case 'triple':
      return [{ id: 'top' }, { id: 'bottom-left' }, { id: 'bottom-right' }]
    case 'quad':
      return [
        { id: 'top-left' }, 
        { id: 'top-right' },
        { id: 'bottom-left' },
        { id: 'bottom-right' }
      ]
    default:
      return [{ id: 'main' }]
  }
})

// 初始化 VTK.js
onMounted(async () => {
  if (!container.value) {
    console.error('Container element not found')
    return
  }

  if (!volumeData.value) {
    ElMessage.error('未找到影像数据')
    router.push('/files')
    return
  }

  try {
    // 创建渲染窗口
    renderWindow = vtkFullScreenRenderWindow.newInstance({
      container: container.value,
      background: [0, 0, 0]
    })

    renderer = renderWindow.getRenderer()
    
    // 设置体渲染
    await setupVolume()
  } catch (error) {
    console.error('Error initializing viewer:', error)
    ElMessage.error('初始化查看器失败')
  }
})

// 清理
onUnmounted(() => {
  if (renderWindow) {
    renderWindow.delete()
  }
})

// 设置体渲染
const setupVolume = async () => {
  try {
    volumeMapper = vtkVolumeMapper.newInstance()
    volumeMapper.setInputData(volumeData.value)

    volumeActor = vtkVolume.newInstance()
    volumeActor.setMapper(volumeMapper)

    // 设置颜色和不透明度传输函数
    const colorFunction = vtkColorTransferFunction.newInstance()
    const opacityFunction = vtkPiecewiseFunction.newInstance()

    // 根据数据类型设置合适的传输函数
    await setupTransferFunctions(colorFunction, opacityFunction)

    volumeActor.getProperty().setRGBTransferFunction(0, colorFunction)
    volumeActor.getProperty().setScalarOpacity(0, opacityFunction)

    renderer.addVolume(volumeActor)
    renderer.resetCamera()
    renderWindow.render()
  } catch (error) {
    console.error('Error setting up volume:', error)
    throw error
  }
}

// 设置传输函数
const setupTransferFunctions = async (color: any, opacity: any) => {
  // 这里设置颜色映射
  color.addRGBPoint(-1000, 0.3, 0.3, 1.0)
  color.addRGBPoint(-500, 0.3, 1.0, 0.3)
  color.addRGBPoint(0, 1.0, 0.3, 0.3)
  color.addRGBPoint(500, 1.0, 1.0, 0.3)

  // 设置不透明度映射
  opacity.addPoint(-1000, 0.0)
  opacity.addPoint(-500, 0.2)
  opacity.addPoint(0, 0.4)
  opacity.addPoint(500, 0.8)

  await Promise.resolve()
}

// 更新布局
const setLayout = (type: string) => {
  currentLayout.value = type
  // 重新设置渲染视图
  setupViews()
}

// 设置渲染模式
const setRenderMode = (mode: string) => {
  currentMode.value = mode
  if (!volumeMapper) return

  switch (mode) {
    case 'mip':
      volumeMapper.setBlendMode(vtkVolumeMapper.BlendMode.MAXIMUM_INTENSITY_BLEND)
      break
    case 'average':
      volumeMapper.setBlendMode(vtkVolumeMapper.BlendMode.AVERAGE_INTENSITY_BLEND)
      break
    case 'composite':
      volumeMapper.setBlendMode(vtkVolumeMapper.BlendMode.COMPOSITE_BLEND)
      break
  }
  renderWindow.render()
}

// 更新体渲染属性
const updateVolumeProperty = () => {
  if (!volumeActor) return

  const property = volumeActor.getProperty()
  property.setOpacity(volumeOpacity.value / 100)
  property.setAmbient(brightness.value / 100)
  property.setDiffuse(contrast.value / 100)

  renderWindow.render()
}

// 更新切割平面
const updateClipPlanes = () => {
  if (!volumeMapper) return

  volumeMapper.setClippingPlanes([
    [1, 0, 0, -clipPlanes.value.sagittal],
    [0, 1, 0, -clipPlanes.value.coronal],
    [0, 0, 1, -clipPlanes.value.axial]
  ])

  renderWindow.render()
}

// 重置视图
const resetView = () => {
  if (!renderer) return
  renderer.resetCamera()
  renderWindow.render()
}

// 截图
const takeScreenshot = () => {
  if (!renderWindow) return
  const screenshot = renderWindow.captureImage()
  // 处理截图，例如下载或预览
}

// 设置多视图
const setupViews = () => {
  // 实现多视图布局
  // 这里需要根据 currentLayout 创建多个渲染器和视图
}

// 添加到script部分
const goToSegmentation = () => {
  if (!route.params.id) {
    ElMessage.warning('未找到影像ID')
    return
  }
  router.push({
    name: 'segmentation',
    params: { id: route.params.id }
  })
}
</script>

<style scoped>
.volume-viewer {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #000;
  position: relative;
}

.toolbar {
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  gap: 20px;
  align-items: center;
  z-index: 1;
}

.viewer-container {
  flex: 1;
  position: relative;
}

.vtk-view {
  position: absolute;
}

.layout-single {
  width: 100%;
  height: 100%;
}

.layout-double {
  width: 50%;
  height: 100%;
}

.layout-double:first-child {
  left: 0;
}

.layout-double:last-child {
  right: 0;
}

.layout-triple {
  width: 50%;
  height: 50%;
}

.layout-triple:first-child {
  width: 100%;
  height: 50%;
  top: 0;
}

.layout-triple:nth-child(2) {
  left: 0;
  bottom: 0;
}

.layout-triple:last-child {
  right: 0;
  bottom: 0;
}

.layout-quad {
  width: 50%;
  height: 50%;
}

.layout-quad:nth-child(1) {
  left: 0;
  top: 0;
}

.layout-quad:nth-child(2) {
  right: 0;
  top: 0;
}

.layout-quad:nth-child(3) {
  left: 0;
  bottom: 0;
}

.layout-quad:nth-child(4) {
  right: 0;
  bottom: 0;
}

.side-panel {
  position: absolute;
  right: 20px;
  top: 80px;
  width: 300px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.panel-content {
  padding: 15px;
}

.view-controls {
  display: flex;
  gap: 10px;
}
</style> 